import React, { ReactElement, useState, useRef } from 'react'
import style from './index.module.less'
import RoleList, { RoleListSchema } from './components/roleList'
import AuthorityList from './components/authorityList'
import { RoleShcema } from '@src/components/schema/role'
import { updateRoleRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import { message } from 'antd'

async function updateRule (r: RoleShcema | null, rules: string[], refreshData: () => void): Promise<void> {
  if (r === null) {
    return undefined
  }
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(updateRoleRequest(r, rules))
  h()
  if (e === null) {
    refreshData()
  }
}

function Main (): ReactElement {
  const roleRef = useRef<RoleListSchema>(null)
  const [currentRole, setCurrentRole] = useState<RoleShcema | null>(null)
  return (
    <div className={style.container}>
      <div className={style.body}>
        <div className={style.left}>
          <RoleList ref={roleRef} currentRole={currentRole} setCurrentRole={setCurrentRole} />
        </div>
        <div className={style.right}>
          <AuthorityList currentRole={currentRole} onChange={async (d) => await updateRule(currentRole, d, () => roleRef.current?.updateCurrentRoleRules(d))} />
        </div>
      </div>
    </div>
  )
}

export default Main
